package cn.yunhe.controller;

import cn.yunhe.entity.Product;
import cn.yunhe.service.ProductService;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;

import java.util.List;

@Controller
@RequestMapping("/product")
public class ProductController {

    @Autowired
    private ProductService productService;

    @RequestMapping("/findAll")
    public String findAll(Model model,
                          @RequestParam(value = "page", defaultValue = "1") Integer page,
                          @RequestParam(value = "size", defaultValue = "5") Integer size) {
        PageHelper.startPage(page, size);
        List<Product> productList = productService.findAll();
        PageInfo<Product> info = new PageInfo<>(productList);
        model.addAttribute("pageInfo", info);
        return "product-list";
    }

    @RequestMapping("/save")
    public String insertProduct(Product product) {
        productService.insertProduct(product);
        return "redirect:findAll";
    }

    @RequestMapping("/deleteById")
    public String deleteById(Integer id) {
        productService.deleteById(id);
        return "redirect:findAll";
    }

    @RequestMapping("/editById")
    public String editById(Integer id, Model model) {
        Product product = productService.selectById(id);
        model.addAttribute("product", product);
        return "product-edit";

    }

    @RequestMapping("/edit")
    public String update(Product product) {
        productService.updateById(product);
        return "redirect:findAll";

    }

    @RequestMapping("/selectDelete")
    public String selectDelete(Integer[] ids) {
        productService.selectDelete(ids);
        return "redirect:findAll";
    }

    @RequestMapping("/findById")
    public String findById(Integer id,Model model) {
     Product product =  productService.selectById(id);
        System.out.println(product);
     model.addAttribute("product",product);
     return "product-show";
    }

}
